﻿using System;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Reactor.Client.Messages;

namespace Reactor.Client.ViewModel
{
    public abstract class DialogViewModel : ViewModelBase
    {
        #region Fields

        private readonly IMessenger _messenger;
        private object _formContent;
        private bool _isBusy;
        private bool _canSave;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="DialogViewModel"/> class.
        /// </summary>
        /// <param name="messenger">An instance of a <see cref="T:GalaSoft.MvvmLight.Messaging.Messenger"/>
        /// used to broadcast messages to other objects. If null, this class
        /// will attempt to broadcast using the Messenger's default
        /// instance.</param>
        protected DialogViewModel(IMessenger messenger)
        {
            if (messenger == null) throw new ArgumentNullException("messenger");

            _messenger = messenger;
        }

        public object FormContent
        {
            get { return _formContent; }
            set
            {
                if (value == _formContent) return;

                _formContent = value;
                RaisePropertyChanged("FormContent");
            }
        }

        public ICommand SubmitCommand
        {
            get { return new RelayCommand(OnSubmit); }
        }

        public ICommand CancelCommand
        {
            get { return new RelayCommand(OnCancel); }
        }

        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (value == _isBusy) return;

                _isBusy = value;

                if (_isBusy)
                    CanSave = false;

                RaisePropertyChanged("IsBusy");
            }
        }

        public bool CanSave
        {
            get { return _canSave; }
            set
            {
                if (value == _canSave) return;

                _canSave = value;
                RaisePropertyChanged("CanSave");
            }
        }

        protected abstract void OnSubmit();

        protected virtual void OnCancel()
        {
            _messenger.Send(new CloseModalDialogRequest());
        }
    }
}
